/*
// 用户行为监控Repository - 已注释
// 如需重新启用，请取消注释

using Dapper;
using Lzfy_Refund_Service.Models;
using Lzfy_Refund_Service.Services;
using System.Data;

namespace Lzfy_Refund_Service.Repositories
{
    public class UserBehaviorRepository : IUserBehaviorRepository
    {
        private readonly IDbConnection _connection;
        private readonly ILogger<UserBehaviorRepository> _logger;

        public UserBehaviorRepository(IDbConnection connection, ILogger<UserBehaviorRepository> logger)
        {
            _connection = connection;
            _logger = logger;
        }

        #region 行为日志相关

        public async Task<long> CreateBehaviorLogAsync(UserBehaviorLog log)
        {
            const string sql = @"
                INSERT INTO lzfy_user_behavior_log 
                (user_id, user_name, session_id, task_detail_id, patient_id, action_type, action_data, 
                 timestamp, page_url, user_agent, ip_address, created_at)
                VALUES 
                (@UserId, @UserName, @SessionId, @TaskDetailId, @PatientId, @ActionType, @ActionData, 
                 @Timestamp, @PageUrl, @UserAgent, @IpAddress, GETDATE());
                SELECT CAST(SCOPE_IDENTITY() as bigint);";

            return await _connection.QuerySingleAsync<long>(sql, log);
        }

        public async Task<IEnumerable<UserBehaviorLog>> GetBehaviorLogsBySessionAsync(string sessionId)
        {
            const string sql = @"
                SELECT * FROM lzfy_user_behavior_log 
                WHERE session_id = @SessionId 
                ORDER BY timestamp";

            return await _connection.QueryAsync<UserBehaviorLog>(sql, new { SessionId = sessionId });
        }

        public async Task<IEnumerable<UserBehaviorLog>> GetBehaviorLogsByUserAsync(string userId, DateTime? startDate = null, DateTime? endDate = null)
        {
            var sql = "SELECT * FROM lzfy_user_behavior_log WHERE user_id = @UserId";
            var parameters = new { UserId = userId, StartDate = startDate, EndDate = endDate };

            if (startDate.HasValue)
                sql += " AND timestamp >= @StartDate";
            if (endDate.HasValue)
                sql += " AND timestamp <= @EndDate";

            sql += " ORDER BY timestamp DESC";

            return await _connection.QueryAsync<UserBehaviorLog>(sql, parameters);
        }

        #endregion

        #region 操作会话相关

        public async Task<long> CreateOperationSessionAsync(UserOperationSession session)
        {
            const string sql = @"
                INSERT INTO lzfy_user_operation_session 
                (session_id, user_id, user_name, task_detail_id, patient_id, patient_name, phone_number, 
                 start_time, is_completed, created_at)
                VALUES 
                (@SessionId, @UserId, @UserName, @TaskDetailId, @PatientId, @PatientName, @PhoneNumber, 
                 @StartTime, @IsCompleted, GETDATE());
                SELECT CAST(SCOPE_IDENTITY() as bigint);";

            return await _connection.QuerySingleAsync<long>(sql, session);
        }

        public async Task<UserOperationSession?> GetOperationSessionAsync(string sessionId)
        {
            const string sql = "SELECT * FROM lzfy_user_operation_session WHERE session_id = @SessionId";
            return await _connection.QuerySingleOrDefaultAsync<UserOperationSession>(sql, new { SessionId = sessionId });
        }

        public async Task<bool> UpdateOperationSessionAsync(UserOperationSession session)
        {
            const string sql = @"
                UPDATE lzfy_user_operation_session SET
                    phone_view_time = @PhoneViewTime,
                    first_input_time = @FirstInputTime,
                    last_input_time = @LastInputTime,
                    input_char_count = @InputCharCount,
                    input_duration = @InputDuration,
                    contact_result = @ContactResult,
                    user_notes = @UserNotes,
                    save_time = @SaveTime,
                    total_duration = @TotalDuration,
                    phone_to_save_duration = @PhoneToSaveDuration,
                    is_completed = @IsCompleted,
                    risk_score = @RiskScore,
                    risk_factors = @RiskFactors,
                    updated_at = GETDATE()
                WHERE session_id = @SessionId";

            var rowsAffected = await _connection.ExecuteAsync(sql, session);
            return rowsAffected > 0;
        }

        public async Task<IEnumerable<UserOperationSession>> GetUserOperationSessionsAsync(string userId, DateTime startDate, DateTime endDate)
        {
            const string sql = @"
                SELECT * FROM lzfy_user_operation_session 
                WHERE user_id = @UserId AND start_time >= @StartDate AND start_time < @EndDate
                ORDER BY start_time DESC";

            return await _connection.QueryAsync<UserOperationSession>(sql, new { UserId = userId, StartDate = startDate, EndDate = endDate });
        }

        public async Task<IEnumerable<UserOperationSession>> GetSuspiciousSessionsAsync(decimal minRiskScore)
        {
            const string sql = @"
                SELECT * FROM lzfy_user_operation_session 
                WHERE risk_score >= @MinRiskScore 
                ORDER BY risk_score DESC, start_time DESC";

            return await _connection.QueryAsync<UserOperationSession>(sql, new { MinRiskScore = minRiskScore });
        }

        #endregion

        #region 分析规则相关

        public async Task<IEnumerable<BehaviorAnalysisRule>> GetActiveRulesAsync()
        {
            const string sql = "SELECT * FROM lzfy_behavior_analysis_rules WHERE is_active = 1";
            return await _connection.QueryAsync<BehaviorAnalysisRule>(sql);
        }

        public async Task<decimal> CalculateUserAverageOperationTimeAsync(string userId)
        {
            const string sql = @"
                SELECT AVG(CAST(total_duration as decimal)) 
                FROM lzfy_user_operation_session 
                WHERE user_id = @UserId AND is_completed = 1 AND total_duration IS NOT NULL";

            var result = await _connection.QuerySingleOrDefaultAsync<decimal?>(sql, new { UserId = userId });
            return result ?? 0;
        }

        #endregion

        #region 统计相关

        public async Task<UserBehaviorStatistics?> GetUserStatisticsAsync(string userId, DateTime date)
        {
            const string sql = "SELECT * FROM lzfy_user_behavior_statistics WHERE user_id = @UserId AND stat_date = @Date";
            return await _connection.QuerySingleOrDefaultAsync<UserBehaviorStatistics>(sql, new { UserId = userId, Date = date.Date });
        }

        public async Task<bool> CreateOrUpdateStatisticsAsync(UserBehaviorStatistics statistics)
        {
            const string checkSql = "SELECT COUNT(1) FROM lzfy_user_behavior_statistics WHERE user_id = @UserId AND stat_date = @StatDate";
            var exists = await _connection.QuerySingleAsync<int>(checkSql, statistics) > 0;

            string sql;
            if (exists)
            {
                sql = @"
                    UPDATE lzfy_user_behavior_statistics SET
                        total_operations = @TotalOperations,
                        completed_operations = @CompletedOperations,
                        avg_duration = @AvgDuration,
                        min_duration = @MinDuration,
                        max_duration = @MaxDuration,
                        suspicious_operations = @SuspiciousOperations,
                        avg_risk_score = @AvgRiskScore,
                        updated_at = GETDATE()
                    WHERE user_id = @UserId AND stat_date = @StatDate";
            }
            else
            {
                sql = @"
                    INSERT INTO lzfy_user_behavior_statistics 
                    (user_id, stat_date, total_operations, completed_operations, avg_duration, 
                     min_duration, max_duration, suspicious_operations, avg_risk_score, created_at)
                    VALUES 
                    (@UserId, @StatDate, @TotalOperations, @CompletedOperations, @AvgDuration, 
                     @MinDuration, @MaxDuration, @SuspiciousOperations, @AvgRiskScore, GETDATE())";
            }

            var rowsAffected = await _connection.ExecuteAsync(sql, statistics);
            return rowsAffected > 0;
        }

        #endregion
    }
}
*/